<?php
    if (!isset($_POST['username']) || !isset($_POST['password']) || $_POST['username'] != "maebert" || md5($_POST['password']) != "3223ae727f9fb08003986cda10459242" )
    header( 'Location: index.php?error=yes' )  
?>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN"
   "http://www.w3.org/TR/html4/strict.dtd">

<html lang="en">
<head>
	<meta http-equiv="Content-Type" content="text/html; charset=utf-16">
	<title>parseo3</title>
	<meta name="author" content="Manuel Ebert">
	<link rel="stylesheet" type="text/css" href="parseo3.css"/>
	<script src="../lib/prototype.js" type="text/javascript"></script>
	<script src="../lib/scriptaculous.js" type="text/javascript"></script>
	
	<!-- Date: 2009-05-11 -->
	<script type="text/javascript" language="javascript">
		function delete_course(array, hash) {
			$("tr"+hash).fade();
			array[hash] = "";
		}
	
		function show_autosearch(hash) {
			$("td"+hash).innerHTML = '<form onSubmit="return false;" method="POST"><input onkeypress="check_escape(event, \''+hash+'\')" type="text" name="coursename" id="coursename'+hash+'"/><div class="autocomplete" id="courselist'+hash+'" style="display:none"></div></form>';
			$("td"+hash).setAttribute('onclick', '');
			new Ajax.Autocompleter("coursename"+hash, "courselist"+hash, "parser_autocomplete.php", {
				afterUpdateElement : add_instance,
				parameters: "hash="+hash
			});
			$("coursename"+hash).focus();
		}
		
		function check_escape(e, hash) {
			var kC  = (window.event) ?    // MSIE or Firefox?
				event.keyCode : e.keyCode;
			var Esc = (window.event) ?   
				27 : e.DOM_VK_ESCAPE // MSIE : Firefox
			if(kC==Esc) {
				$("td"+hash).innerHTML = new_courses[hash][0]+"<br /><i>"+hash+"</i>";
				$("td"+hash).setAttribute('onclick', 'show_autosearch(\''+hash+'\');');
			}		 
		}
		
		function add_instance(text, li) {
			result = li.id.split(";");
			course = result[0];
			hash = result[1];
			$("tr"+hash).fade();
			new_instances[course] = new_courses[hash];
			new_courses[hash] = "";
			
		}
		
		function save_data(type) {
			if (type == "new") {
				todo = 0;
				//$("tablenew").morph("opacity: .4;");
				for (hash in new_courses) {
					if (new_courses[hash] != "") {
						todo++;
						$("delb"+hash).innerHTML = "SEND";
						$("delb"+hash).style.backgroundColor = "#c60";
						$("delb"+hash).style.color = "#fff";
						course = new_courses[hash];
						course['hash'] = hash;
						
						new Ajax.Request("insertcourse.php", {
							method: 'post',
							parameters: course,
							onSuccess: function(transport) {
								$("delb"+transport.responseText).innerHTML = "DONE";
								$("delb"+transport.responseText).style.backgroundColor = "#393";
								if (--todo==0) $("sectionnew").fade();
							},
							onFailure: function(transport) {
								$("delb"+transport.responseText).innerHTML = "ERROR";
								$("delb"+transport.responseText).style.backgroundColor = "#933";
							}
						});
					}
						
				}
				
			}
			
			else if (type == "inst") {
				todo = 0;
				//$("tablenew").morph("opacity: .4;");
				for (hash in new_instances) {
					if (new_instances[hash] != "") {
						todo++;
						$("delb"+hash).innerHTML = "SEND";
						$("delb"+hash).style.backgroundColor = "#c60";
						$("delb"+hash).style.color = "#fff";
						course = new_instances[hash];
						course['hash'] = hash;
						
						new Ajax.Request("insertinstance.php", {
							method: 'post',
							parameters: course,
							onSuccess: function(transport) {
								$("delb"+transport.responseText).innerHTML = "DONE";
								$("delb"+transport.responseText).style.backgroundColor = "#393";
								if (--todo==0) $("sectioninst").fade();
							},
							onFailure: function(transport) {
								$("delb"+transport.responseText).innerHTML = "ERROR";
								$("delb"+transport.responseText).style.backgroundColor = "#933";
							}
						});
					}
						
				}
				
			}
			
		}
	
	</script>
</head>
<body>
<div id="content">
	<div id="header">
	</div>


<?php

if (!$_GET['term'] || !$_GET['year']) {
	header("HTTP/1.1 403 Forbidden");
	echo "<h1>Do some ?term=WS&year=2009 to me!</h1>";
} else {
	$year = $_GET['year'];
	$term = $_GET['term'];
	
	
	$comp_areas = array(
		2825 => 'math',
		2826 => 'bio',
		2827 => 'info',
		2828 => 'ai',
		2829 => 'cl',
		2830 => 'psycho',
		2831 => 'ninf',
		2834 => 'phil',
		2832 => '', //'statistik'
		2833 => '' //'logik'
	);

	$all_courses = array();
	$practice_courses = array();

	// Connecting, selecting database
	$dbconn = pg_connect("host=dbserv port=5433 dbname=o2 user=wwwrun password=")
	    or die('Could not connect: ' . pg_last_error());

	// Performing SQL query
	$query = 'SELECT * FROM lec WHERE (year='.$year.' AND term=\''.$term.'\') ORDER BY exam_status ASC';
	$result = pg_query($query) or die('Query failed: ' . pg_last_error());

	$i = 0;


	// Fetch one course after another
	while ($line = pg_fetch_array($result, null, PGSQL_ASSOC)) {
		$l_query = 'select * FROM o3_staff JOIN address_title ON o3_staff.title = address_title.id WHERE o3_staff._o3_id = '.$line['teacher'];
		$l_result = pg_query($l_query) or die('Query failed: ' . pg_last_error());
		$l_line = pg_fetch_array($l_result, null, PGSQL_ASSOC);

	    // write results into variables
		$lecturer = htmlentities($l_line['title'].' '.$l_line['fname'].' '.$l_line['lname'], ENT_QUOTES);
		if ($lecturer==="  ") $lecturer = "N.N.";
		$title = preg_replace('/\(?(Gruppe|Group) *[a1i]\)?/i', '', $line['title']);
		$title = htmlentities($title, ENT_QUOTES);
		$key = 	$line['key'];
		$year = $line['year'];
		$credits = $line['credits'];
		$sem = $line['minsem'];
		$term = $line['term'] === "W" ? true : false;
	
		$area1 = '';
		$area2 = '';
		$comp = '';
	
		// get appropriate areas
		if ($line['CS'] == 't') {if ($area1 == '') $area1 = 'info'; else $area2 = 'info';}
		if ($line['CP'] == 't') {if ($area1 == '') $area1 = 'psycho'; else $area2 = 'psycho';}
		if ($line['PC'] == 't') {if ($area1 == '') $area1 = 'phil'; else $area2 = 'phil';}
		if ($line['MA'] == 't') {if ($area1 == '') $area1 = 'math'; else $area2 = 'math';}
		if ($line['CL'] == 't') {if ($area1 == '') $area1 = 'cl'; else $area2 = 'cl';}
		if ($line['AI'] == 't') {if ($area1 == '') $area1 = 'ai'; else $area2 = 'ai';}
		if ($line['NS'] == 't') {if ($area1 == '') $area1 = 'ninf'; else $area2 = 'ninf';}
		if ($line['NB'] == 't') {if ($area1 == '') $area1 = 'bio'; else $area2 = 'bio';}

		if ($line['exam_status'] >= 2825 && $line['exam_status'] <= 2834) {
			$comp = "comp";	
			$area1 = $comp_areas[$line['exam_status']];
		}
	
		// now we apply some scary heuristics to remove some courses
		if (
			preg_match('/[0-9]\.[x0-9]+a?/', $key) && // only valid keys
			! preg_match('/E N T F .* L L T|ENTF.*LLT|(Gruppe|Group) *([bcdefg23456]|ii+)|\(Seminar II|\(Tutorial\)/i', $title) && // drop if it entfaellt or if it's a tutorial or gruop n>1 of a practice
			$credits != 0 && $title != "" && // Drop if there's nothing in for you...
			! ($comp === $comp && preg_match('/Philosophy of Mind/i', $title) && preg_match('/Seminar/i', $title)) && // Extra case for pom
			! preg_match('/Empirical Methods|.*bungen zur (Statistik|Methodenlehre)|Exercises in Statistics|Versuchsplanung/i', $title) && // Statistics recieves special treatment		
			! ($key === "8.3004" && $year = 2009)
		) {
			// Now all exceptions....
		    if ($comp === "comp" && preg_match('/Philosophy of Mind/i', $title)) {
		        $title = "Introduction to the Philosophy of Mind";
		        $credits = 8;
		       }
	    
			if (preg_match('/studienprojekt/i', $title) || preg_match('/study project/i', $title)) {
				$title = preg_replace('/studienprojekt/i', 'Study Project', $title);
				$title = preg_replace('/(, )?\)?(part|teil) (i+|1|2)\)?/i', '', $title);
				$credits = 24;
			}
			$title = preg_replace('/\(seminar \+ .*bung\)/i', '', $title);
	
			if ($title === "Datenbanken (Practice)" && $key === "6.714" && $year = 2009 && !$term) $title = "Datenbanksysteme (Practice)";
			if ($title === "Analysis I (Practice) (Brun, M.)" && $key === "6.004" && $year == 2005 && !$term) $title = "Analysis I (Practice)";

			if ($title === "Algorithms - Lecture (Algorithmen)") $title = "Informatik A: Algorithmen (Lecture)";
			if ($title === "Agorithms - Practice (Algorithmen)") $title = "Informatik A: Algorithmen (Practice)";

		    if ($comp === "comp" && $area1 === "info" && (preg_match('/algorithmen/i', $title) || preg_match('/informatik a/i', $title))) {
				if (preg_match('/\((Practice|&Uuml;bung|Begleitseminar)\)|^(&uuml;bung(en)?|Begleitseminar) zu/i', $title)) $title = "Informatik A: Algorithmen (Practice)";
				else $title = "Informatik A: Algorithmen";
			}
			if ($comp === "comp" && $area1 === "psycho" && $title === "Cognitive Neuropsychology Part I") $title = "Cognitive Neuropsychology I";
			if ($comp === "comp" && preg_match('/introduction to logic/i', $title)) $title = preg_replace('/Introduction to/', 'Foundations of', $title);
			if ($comp === "comp" && preg_match('/Foundations of Logic I/i', $title)) $title = preg_replace('/ i/i', "", $title);

			if ($comp === "comp" && $area1 === "psycho" && preg_match('/Cognitive Psychology.*Neuropsychology/i')) $title = preg_replace('/Cognitive Psychology.*Neuropsychology/i', 'Cognitive Psychology and Neuropsychology', $title);

			if ($title === "Linear Algebra I - Lecture (Lineare Algebra I)") $title = "Linear Algebra I (Lecture)";
			if ($title === "Linear Algebra I - Practice (Lineare Algebra I)") $title = "Linear Algebra I (Practice)";
			if (preg_match('/Advanced Topics in Action.*Cognition/i', $title)) $title = "Advanced Topics in Action & Cognition";
			if (preg_match('/Action.*Cognition/i', $title)) $title = preg_replace('/Action.*Cognition/', "Action & Cognition", $title);
			if (preg_match('/\((Vorlesung.&uuml;bung|lecture.*practice)\)/i', $title)) $title = preg_replace('/ *\((Vorlesung.&uuml;bung|lecture.*practice)\)/i', '', $title);
			if ($title === "Action & Cognition II, Lecture") $title = "Action & Cognition II";
			if ($title === "Action & Cognition II, Seminar") $title = "Action & Cognition II (Seminar)";
			if ($title === "Einfhrung in die Spieltheorie (Seminar)") $title = "Einfhrung in die Spieltheorie (Practice)";
			if ($title === "Computer Science C - Lecture (Informatik C)") $title = "Informatik C (Lecture)";
			if ($title === "Computer Science C - Practice (Informatik C)") $title = "Informatik C (Practice)";
			if ($title === "Informatik B" && $year == 2007 && $key === "6.700") $title = "Informatik B (Practice)";

			if ($key === "8.1111" && $term && $year == 2008) {
				$credits = 12;
				$area1 = "";
			}

			// Special treatment for statistics
		    if (preg_match('/Statisti[kc]s? II$/i', $title)) {
		        $title = "Statistik II";
		        $area1 = "psycho";
		        $credits = 12;
	    	    $all_courses[$i] = array($title, $area1, $area2, $comp, $credits, $lecturer, $key, $term, $year, $sem);   
	    	    $i++;        
		    } else if ($line['exam_status'] == 2832 && $comp == "comp" && preg_match('/Statisti[kc]s?( I)?/i', $title)) {
		        $title = "Statistik I";
		        $area1 = "";
		        $credits = 12;
	    	    $all_courses[$i] = array($title, $area1, $area2, $comp, $credits, $lecturer, $key, $term, $year, $sem);   
	    	    $i++;        
		    }
		
		    // Now save practice courses for later 
		    else if (preg_match('/\((Practice|&uuml;bung|Begleitseminar)\)|^(.bung(en)?|Begleitseminar) zu/i', $title)) {
	            $title = preg_replace('/ *\(?(Practice|&uuml;bung(en zu.? )?|Begleitseminar( zu.? )?)\)?/i', '', $title);
	            array_push($practice_courses, array($title, $area1, $area2, $comp, $credits, $lecturer, $key, $term, $year, $sem, false, false));
	        // All other courses will be treated normally
	        } else {
	            $title = preg_replace('/ *\((Lecture|Vorlesung)\)|Vorlesung: /i', '', $title);
	    	    $all_courses[$i] = array($title, $area1, $area2, $comp, $credits, $lecturer, $key, $term, $year, $sem, false, false);   
	    	    $i++;        
	        }
	    
		}
	    pg_free_result($l_result);
	}

	pg_free_result($result);
	$k = $i;

	for ($i = 0; $i < count($all_courses); $i++) {
		if (preg_match('/Informatik B/i', $all_courses[$i][0])) {$all_courses[$i][0] = "Informatik B: Objektorientierte Programmierung in Java"; $all_courses[$i][4] = 12;}
		if (preg_match('/Informatik C/i', $all_courses[$i][0])) {$all_courses[$i][0] = "Informatik C: Grundlagen der Technischen Informatik"; $all_courses[$i][4] = 12;}
		if (preg_match('/Informatik D/i', $all_courses[$i][0])) {$all_courses[$i][0] = "Informatik D: Grundlagen der Thoeretischen Informatik"; $all_courses[$i][4] = 12;}
	}


	// Now go through practice courses, add their credits to the according lectures.

	foreach ($practice_courses as $course) {
	    $found = false;
	    for ($i = 0; !$found && $i<count($all_courses); $i++) {
	        if (
				(
					trim($all_courses[$i][0]) === trim($course[0]) ||
					trim($all_courses[$i][0]) === trim($course[0])." (Seminar)"
				)
				&& 
				$course[7] == $all_courses[$i][7] && // term
				$course[8] == $all_courses[$i][8]
			   ) {// year
	            $all_courses[$i][4] += $course[4];
	            $found = true;
	        }
	    }
	    /*/ No course found
	    if ($i == count($all_courses)) {
	        $all_courses[$i] = $course;
	    }*/
	}

	pg_close($dbconn);

	/* ***************************************************************************
	 * LOOK FOR OLD COURSES IN DATABASE!
	 ****************************************************************************/


	include 'dbconfig.php'; 

	$new_courses = array();
	$new_instances = array();
	$old_courses = array();
	


	echo "<div class='section'><h1>Parsing o3 ah um...</h1><h3>Courses for ".($term?"winter":"summer")." term $year</h3>";
	echo count($all_courses)." courses parsed. <br>";


	echo "Distinct course templates: ".count($course_templates)."<br>";
	echo "Course instances: ".count($course_instances)."<br>";
	echo "</div>";



	foreach ($all_courses as $course) {
		// let's do a hash first
		$hash = md5($course[0].$all_courses[$j][8].$all_courses[$j][7]);
		$title = $course[0];
		
		$query = "SELECT cid FROM course_templates WHERE name = '$title' LIMIT 1";
		$result = mysql_query($query);
		
		
		if (mysql_num_rows($result) == 0) {
			//array_push($new_courses, $course);
			$new_courses[$hash] = $course;
		} else {
			$cid = mysql_fetch_array($result);
			$cid = $cid['cid'];
			$term = $course[7] ? "true" : "false";
			$year = $course[8];
			$query = "SELECT * FROM course_instances WHERE (cid = '$cid' AND year = $year AND term = $term)";
			$result = mysql_query($query);
			
			if (mysql_num_rows($result) == 0) 
				$new_instances[$cid] = $course;
			else
				$old_courses[$hash] = $course;
		}
	}	
	
	function make_table($courses, $type) {
		$title = ($type == "new" ? "New Courses" : ($type == "inst" ? "New instances of old courses" : "Existing courses (skipped)"));
		$array = ($type == "new" ? 'new_courses' : ($type == "inst" ? 'new_instances' : 'old_courses'));

		echo "\n\n<script language='JavaScript'>\n\tvar $array = {\n";
		foreach ($courses as $hash => $course) {
			echo "\t\t'$hash' : Array('".$course[0]."','".$course[1]."','".$course[2]."','".$course[3]."',".$course[4].",'".$course[5]."','".$course[6]."',".($course[7]?"true":"false").",".$course[8].",".$course[9]."),\n";
		}
		echo "};\n";
		echo "</script>\n\n";

		echo "<div class='section' id='section$type'><h2>$title</h2>";
		echo "<table id='table$type'>\n";
		echo "<tr><td colspan='4'>Title</td><td><img src='../bin/badge-2.png' width='12' height='12' /></td><td>Teacher</td><td>Key</td></tr>";

		foreach ($courses as $hash => $course) {
			echo "<tr id='tr$hash'>";
			echo "<td class='badge'>".($course[3] ? "<img width='12' height='12' src='../bin/badge-comp.png' />" : "")."</td>";
			echo "<td class='badge'>".($course[1] ? "<img width='12' height='12' src='../bin/badge-".$course[1].".png' />" : "")."</td>";
			echo "<td class='badge'>".($course[2] ? "<img width='12' height='12' src='../bin/badge-".$course[2].".png' />" : "")."</td>";
			if ($type == "new") echo "<td id='td$hash' class='editbutton' onclick=\"show_autosearch('$hash')\">";
			else echo "<td>";
			echo $course[0]."<br /><i>".$hash."</i></td>";
			echo "<td>".$course[4]."</td>";
			echo "<td>".$course[5]."</td>";
			if ($type != "old")
				echo "<td id='delb$hash' class='deletebutton' onclick=\"delete_course($array, '$hash')\">";
			else echo "<td>";
			echo $course[6]."</td></tr>";
		}
		echo "</table>\n";
		
		if ($type != "old") echo "<div class='okbutton' onclick=\"save_data('$type')\">Submit to Database</div>";
		echo "</div>";
	}

	
	make_table($new_courses, "new");
	make_table($new_instances, "inst");
	make_table($old_courses, "old");
	
/*


	/* Delete old o3 courses
	$query = "DELETE FROM course_templates WHERE external = 0";
	mysql_query($query);*

	foreach ($course_templates as $course) {
		$values = "0, '$course[0]', '$course[1]', '$course[2]', '$course[3]', '$course[4]', $course[5], $course[6], false, false";
		$query = "INSERT INTO course_templates VALUES ($values)";
		mysql_query($query);
	}
	
	/* Delete old o3 courses
	$query = "DELETE FROM course_instances";
	//parse
	mysql_query($query);*
	foreach ($course_instances as $course) {
		$values = "0, '$course[0]', '$course[1]', $course[2], ".($course[3]?"true":"false").", '$course[4]', '$course[5]'";
		$query = "INSERT INTO course_instances VALUES ($values)";
		mysql_query($query);
	}*/
}
?>

	
</div>
</body>
</html>